package com.yun.controller;

//<<<<<<< Updated upstream
import java.io.File;
//=======
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
//>>>>>>> Stashed changes
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
//<<<<<<< Updated upstream
//=======
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

//>>>>>>> Stashed changes
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//<<<<<<< Updated upstream
import org.apache.commons.io.FileUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
//=======
import org.apache.tools.zip.ZipUtil;
//>>>>>>> Stashed changes
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
//<<<<<<< Updated upstream
//=======
import org.springframework.web.bind.annotation.ResponseBody;
//>>>>>>> Stashed changes
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.yun.entity.Files;
import com.yun.entity.Folder;
import com.yun.entity.User;
import com.yun.service.FileService;
import com.yun.service.FolderService;
import com.yun.utils.ZipUtils;

import net.sf.json.JSONArray;

@Controller
public class FileController {
	/**
	 * 文件上传功能
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 */
	@Resource
	private FileService fileServiceImpl;
	@Resource
	private FolderService folderServiceImpl;

	//
	@RequestMapping(value = "/uploadMultiple", method = RequestMethod.POST)
	public String uploadMultiple(Files file, HttpServletRequest request) throws Exception, IOException {
		System.out.println("上传文件:" + file.toString());

		List<MultipartFile> attachment = file.getAttachment();
		List<String> fileNames = new ArrayList<String>();
		System.out.println("attachment是否为空?" + attachment.isEmpty() + ":" + attachment.size());
		if (!attachment.isEmpty() && attachment.size() > 0) {
			for (MultipartFile file1 : attachment) {
				String path = request.getServletContext().getRealPath("/images/");
				System.out.println("path:" + path);
				String fileName = file1.getOriginalFilename();
				fileName = file.getUserId() + "_" + fileName;
				File filePath = new File(path, fileName);
				System.out.println("文件是否存在：" + filePath.exists());
				if (!filePath.getParentFile().exists()) {
					filePath.getParentFile().mkdirs();
				}
				File target = new File(path + File.separator + fileName);
				file1.transferTo(target);
				fileNames.add(fileName);
				// file.setFileName(fileName);
				// file.setFileUrl(path);
				Date day = new Date();
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
				String time = df.format(day);
				long size = file1.getSize();
				// file.setUpTime(df.format(day));
				// file.setFileSize(file1.getSize());
				String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
				int typeId;
				if (suffix.equalsIgnoreCase("txt") || suffix.equalsIgnoreCase("docx")) {
					typeId = 1;

				} else if (suffix.equalsIgnoreCase("mp4")) {
					typeId = 2;
				} else if (suffix.equalsIgnoreCase("png") || suffix.equalsIgnoreCase("jpg")) {
					typeId = 3;
				} else if (suffix.equalsIgnoreCase("mp3")) {
					typeId = 4;
				} else {
					typeId = 5;
				}
				Files file2 = new Files(fileName, path, time, size, typeId, file.getUserId());
				fileServiceImpl.addFile(file2);
				/*
				 * HttpSession session = request.getSession(); User existUser =
				 * (User)session.getAttribute("existUser");
				 * System.out.println(existUser); List<Files> files =
				 * fileServiceImpl.readFile(existUser.getUserId()); int
				 * used_size = 0; for(Files f:files) { used_size +=
				 * f.getFileSize(); } session.setAttribute("used_size",
				 * used_size);
				 */
				getMemorySize(request.getSession());
				System.out.println(file2.toString());
			}
		}
		return "admin";

	}

	@RequestMapping(value = "/showFile")
	public ModelAndView showFile(int typeId, HttpSession session) {
		List<Files> files = new ArrayList<Files>();
		List<Folder> getFolderById = new ArrayList<Folder>();
		User user = (User) session.getAttribute("existUser");
		int userId = user.getUserId();
		if (typeId == 0) {
			getFolderById = folderServiceImpl.getFolderById(userId);
			files = fileServiceImpl.readFile(userId);
			session.setAttribute("folder", getFolderById);
//			System.out.println("fafa"+getFolderById.toString());
		} else {
			Files file1 = new Files(typeId, userId);
			files = fileServiceImpl.readFileByTypeId(file1);
		}

		return new ModelAndView("file", "files", files);
	}

	@RequestMapping(value = "/download")
	public ResponseEntity<byte[]> download(HttpServletRequest request, @RequestParam("fileName") String fileName)
			throws Exception {

		System.out.println("文件名:" + fileName);
		String path = request.getServletContext().getRealPath("/images/");
		System.out.println();
		File file = new File(path + File.separator + fileName);
		if (file.exists()) {
			System.out.println("file exists");
		} else {
			System.out.println("file not exists, create it ...");
		}

		HttpHeaders headers = new HttpHeaders();
		String downloadFileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
		headers.setContentDispositionFormData("attachment", downloadFileName);
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers,
				HttpStatus.CREATED);
		return responseEntity;
		/*
		 * System.out.println(fileName); return null;
		 */
		// =======
		// return new ModelAndView("file","files",files);
		// >>>>>>> Stashed changes
	}

	/**
	 * 通过文件Id删除文件（数据库与文件夹中信息）
	 * 
	 * @param fileId
	 * @return
	 */
	@RequestMapping(value = "/delFileByFileId")
	@ResponseBody
	public String delFileByFileId(@RequestBody Files files, HttpSession session) {
		System.out.println("删除文件Id:" + files.getFileId());
		int delResult = fileServiceImpl.delFileByFileId(files.getFileId());
		System.out.println("删除成功与否？" + delResult);

		// 在FileServiceImpl中实现对文件夹中文件的删除.

		if (delResult <= 0) {
			return "no";
		} else {
			getMemorySize(session);
			return "ok";
		}
	}

	@RequestMapping(value = "/show_attach", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public void show_attach(HttpServletRequest request, HttpServletResponse response) {
		FileInputStream bis = null;
		OutputStream os = null;
		try {
			String path = request.getParameter("fileUrl");// 网络图片地址
			System.out.println("网络图片地址:" + path);
			response.setContentType("text/html; charset=UTF-8");
			String type = request.getParameter("type");
			if ("pdf".equalsIgnoreCase(type)) {
				response.setContentType("application/pdf");
			} else {
				response.setContentType("image/" + type);
			}
			bis = new FileInputStream(path);
			os = response.getOutputStream();
			int count = 0;
			byte[] buffer = new byte[1024 * 1024];
			while ((count = bis.read(buffer)) != -1) {
				os.write(buffer, 0, count);
			}
			os.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 重新统计用户内存
	 * 
	 * @param session
	 */
	public void getMemorySize(HttpSession session) {
		User existUser = (User) session.getAttribute("existUser");
		System.out.println(existUser);
		List<Files> files = fileServiceImpl.readFile(existUser.getUserId());
		int used_size = 0;
		for (Files f : files) {
			used_size += f.getFileSize();
		}
		session.setAttribute("used_size", used_size);
	}

	@RequestMapping(value = "/downZip")
	@ResponseBody
	public void downZip(@RequestBody String ids, HttpServletRequest request, HttpServletResponse response)
			throws Exception { // 注意因为我的数组传递过来不是对象形式只是[1,2,3,4]形式，接收的形参用的是String，需要注意，所以不能转为JSONObject
		List<Files> list = new ArrayList<Files>();
		List<File> fileList = new ArrayList<File>();
		JSONArray json = JSONArray.fromObject(ids);
		if (json.size() > 0) {
			for (int i = 0; i < json.size(); i++) {
				int fileId = Integer.parseInt((String) json.get(i));
				Files files = fileServiceImpl.selectByFileId(fileId);
				list.add(files);
				File file = new File(files.getFileUrl() + files.getFileName());
				fileList.add(file);
			}
		}
		System.out.println("fileList:" + fileList.toString());
		// downLoadFiles(fileList, request, response);
		for (Iterator<Files> it = list.iterator(); it.hasNext();) {

			Files file = it.next();
			System.out.println("not you:" + file.toString());
			ZipUtils.doCompress(file.getFileUrl() + file.getFileName(), file.getFileUrl() + file.getFileName() + ".zip");
		}
	}
}
